package sk.tuke.constraintbuilder.utils;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;

public class MyJdtUtils {
	
	public static List<IFile> getJavaFilesFromProject(IProject project) throws CoreException{
		List<IFile> files = new ArrayList<>();
		if(JavaCore.create(project) instanceof IJavaProject){
			IResource[] projectResources = null;
			try {
				projectResources = project.members();
			} catch (CoreException e) {
				e.printStackTrace();
			}
			getJavaFilesFromResources(files, projectResources);
		}
		return files;
	}
	
	private static void getJavaFilesFromResources(List<IFile> files, IResource[] resources) throws CoreException{
		for (int j = 0; j < resources.length; j++) {
			if(resources[j] instanceof IFile){
				if(JavaCore.create(resources[j]) instanceof ICompilationUnit){
					IJavaElement javaElement = JavaCore.create(resources[j]);
					if(javaElement.getResource() instanceof IFile)
						files.add((IFile) javaElement.getResource());
				}
			}
			else if(resources[j] instanceof IFolder){
				getJavaFilesFromResources(files, ((IFolder) resources[j]).members());
			}
		}
	 }
	
	public static IType findTypeInProject(String typeName, IJavaProject javaProject){
			try {
				List<IFile> files = getJavaFilesFromProject(javaProject.getProject());
				for (IFile iFile : files) {
					IJavaElement javaElement = JavaCore.create(iFile);
					IType[] type = ((ICompilationUnit) javaElement).getAllTypes();
					for (int k = 0; k < type.length; k++) {
						if(!type[k].isMember()){
							if(type[k].getElementName().equals(typeName)){
								return type[k];
							}
						}
					}
				}	
			} catch (CoreException e) {
				e.printStackTrace();
			}
		return null;
		
	}

}
